package com.szzg10.thinking.chapter18;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class SerialCtl implements Serializable {

	public static void main(String[] args) throws IOException, ClassNotFoundException {
		SerialCtl serialCtl = new SerialCtl("a", "b");
		System.out.println("Before---");
		System.out.println(serialCtl);
		System.out.println();
		
		//serializable
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
		objectOutputStream.writeObject(serialCtl);
		objectOutputStream.close();
		
		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
		ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
		serialCtl = (SerialCtl)objectInputStream.readObject();
		
		System.out.println("After---");
		System.out.println(serialCtl);
		objectInputStream.close();
	}
	
	private String a;
	private transient String b;
	
	public SerialCtl(String a, String b) {
		this.a = "no transient: " + a;
		this.b = "transient: " + b;
	}
	
	@Override
	public String toString() {
		return a + '\n' + b;
	}
	
	private void writeObject(ObjectOutputStream objectOutputStream) throws IOException, ClassNotFoundException {
		objectOutputStream.defaultWriteObject();
		objectOutputStream.writeObject(b);
	}
	
	private void readObject(ObjectInputStream objectInputStream) throws IOException, ClassNotFoundException {
		objectInputStream.defaultReadObject();
		b = (String)objectInputStream.readObject();
	}
}
